<script>
import { ref } from 'vue';

export default {
  name: 'UserManagement',
  setup() {
  // 从 localStorage 中读取用户数据
  const users = ref(JSON.parse(localStorage.getItem('users')) || []);
  const isEditing = ref(false);

  // 从 localStorage 中读取当前登录用户
  const currentUser = ref(JSON.parse(localStorage.getItem('currentUser')));

  const selectUser = (user) => {
    if (user.id === currentUser.value?.id) {
      return; // 如果点击的是当前登录用户，不做任何操作
    }

    const confirmSwitch = confirm(`切换账号为 ${user.name}？`);
    if (confirmSwitch) {
      currentUser.value = user;
      localStorage.setItem('currentUser', JSON.stringify(user)); // 更新当前登录用户
      users.value.forEach((u) => {
        u.selected = u.id === user.id; // 更新选中状态
      });
      alert(`已切换账号为 ${user.name}`);
    }
  };

  const addUser = () => {
    // 添加用户的逻辑
    console.log('添加或注册账号');
  };

  const deleteUser = (userId) => {
    users.value = users.value.filter(user => user.id !== userId);
    localStorage.setItem('users', JSON.stringify(users.value)); // 更新 localStorage
  };

  const toggleEdit = () => {
    isEditing.value = !isEditing.value;
  };

  return {
    selectUser,
    addUser,
    deleteUser,
    toggleEdit,
    users,
    isEditing,
    currentUser,
  };
}
}
</script>

<template>
  <div class="user-management">
    <div class="header">
      <router-link to="/home" class="back-button">←</router-link>
      <h2>{{ $t('UserManagement.header.title') }}</h2>
      <span class="edit-button" @click="toggleEdit">
        {{ isEditing ? $t('UserManagement.header.done') : $t('UserManagement.header.edit') }}
      </span>
    </div>

    <div class="user-list">
      <div
        v-for="user in users"
        :key="user.id"
        class="user-item"
        @click="selectUser(user)"
      >
        <img :src="user.avatar" alt="头像" class="user-avatar" />
        <div class="user-info">
          <span class="user-name">{{ user.name }}</span>
          <span class="user-phone">{{ user.phone }}</span>
        </div>
        <span v-if="user.id === currentUser?.id" class="checkmark">✔️</span>
        <button v-if="isEditing" class="delete-button" @click.stop="deleteUser(user.id)">{{ $t('UserManagement.addUser.delete') }}</button>
      </div>
      <div class="add-user" @click="addUser">
        <router-link to="/login" class="icon-text-block">
          <span class="add-icon">+</span>
          <span>{{ $t('UserManagement.addUser.text') }}</span>
        </router-link>
      </div>
    </div>
  </div>
</template>

<style scoped>
@import "/src/css/base.css";
@import "/src/css/user/index.css";

.delete-button {
  margin-left: auto;
  background-color: #ff4d4f;
  color: white;
  border: none;
  padding: 5px 10px;
  border-radius: 4px;
  cursor: pointer;
}

.delete-button:hover {
  background-color: #ff7875;
}
</style>
